<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="g_t('fleet.车辆日程')"
    width="850px"
    :before-close="handleClose"
    body-class="dialog-table-class"
  >
    <div class="content-container">
      <el-row justify="space-between" class="dialog-table-filter">
        <div class="row-left">
          <Date
            v-model="listParams.time"
            class="item"
            picker-type="2"
            :disabled-date="disabledDate"
          />
          <SelectCustomer
            :key="customerKey"
            v-model="listParams.customerId"
            class="item"
            :placeholder="$t('fleet.地区')"
          />
          <TextInput
            v-model="listParams.vehiclePlate"
            class="item"
            clearable
            :placeholder="$t('fleet.荷载人数')"
          />
          <el-button type="primary" @click="handleQuery">{{
            $t('public.search')
          }}</el-button>
          <el-button plain @click="handleReset">{{
            $t('public.reset')
          }}</el-button>
        </div>
        <div class="row-right">
          <el-button v-if="type === 'add'" type="primary" @click="handleCreate"
            >+ {{ $t('public.create') }}</el-button
          >
        </div>
      </el-row>
      <div class="base-table-container">
        <BaseTable
          ref="refContentTable"
          v-loading="loading"
          :data="tableData"
          row-key="id"
        >
          <TableColumn
            prop="vehiclePlate"
            align="left"
            label=""
            :column-width="columnWidthObj.vehiclePlate"
          >
            <template #default="{ row }">
              <div>车牌号：{{ row.vehicleEntity?.vehiclePlate || '--' }}</div>
              <div>荷载人数：{{ row.vehicleEntity?.seatCount || '--' }}</div>
            </template>
          </TableColumn>
          <TableColumn v-for="column in columns" :label="column">
            <template #default="{ row }">
              <span>{{ row.vehicleEntity?.vehiclePlate || '--' }}</span>
            </template>
          </TableColumn>
          <TableColumn
            prop="vehiclePlate"
            :label="$t('fleet.licensePlate')"
            :column-width="columnWidthObj.vehiclePlate"
          >
            <template #default="{ row }">
              <span>{{ row.vehicleEntity?.vehiclePlate || '--' }}</span>
            </template>
          </TableColumn>
          <TableColumn
            prop="regionCode"
            :label="$t('fleet.passPlace')"
            :column-width="columnWidthObj.regionCode"
          >
            <template #default="{ row }">
              <div>
                {{ g_utils.getRegionName(row.startRegionCode) }}
              </div>
              ~
              <div>
                {{ g_utils.getRegionName(row.endRegionCode) }}
              </div>
            </template>
          </TableColumn>
          <TableColumn
            prop="detailAddress"
            :label="$t('public.detailAddress')"
            :column-width="columnWidthObj.detailAddress"
          >
            <template #default="{ row }">
              <div>{{ row.startAddress }}</div>
              ~
              <div>{{ row.endAddress }}</div>
            </template>
          </TableColumn>
          <TableColumn
            prop="createTime"
            :label="$t('fleet.passTime')"
            :column-width="columnWidthObj.createTime"
          >
            <template #default="{ row }">
              <div>{{ row.startTime }}</div>
              ~
              <div>{{ row.endTime }}</div>
            </template>
          </TableColumn>
          <TableColumn
            prop="action"
            fixed="right"
            :label="$t('public.action')"
            :column-width="columnWidthObj.action"
          >
            <template #default="{ row }">
              <el-button text @click="handleDetailDialog(row)">
                {{ $t('public.detail') }}
              </el-button>
              <el-button
                v-if="type === 'add'"
                text
                @click="handleEditDialog(row)"
              >
                {{ $t('public.edit') }}
              </el-button>
              <el-button
                v-if="type === 'add'"
                text
                :disabled="row.orderId.length"
                @click="handleDelete(row)"
              >
                {{ $t('public.delete') }}
              </el-button>
            </template>
          </TableColumn>
        </BaseTable>
        <BasePagination
          v-model:page-size="pageSize"
          v-model:current-page="pageNum"
          :total="total"
          @change="getTableList()"
        />
      </div>
      <!-- 新建 -->
      <AddOrEditSchedule
        v-if="addOrEditVisible"
        :id="rowId"
        v-model="addOrEditVisible"
        :vehicle-id="props.vehicleId"
        :type="addOrEditType"
        @update="handleQuery"
      />
      <!-- 详情 -->
      <ScheduleDetailDialog
        v-if="detailVisible"
        :id="rowId"
        v-model="detailVisible"
      />
    </div>
    <template #footer>
      <div class="detail-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.close')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
import AddOrEditSchedule from './AddOrEditSchedule.vue'
import ScheduleDetailDialog from './ScheduleDetailDialog.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | view
  },
  vehicleId: {
    type: String,
    default: ''
  },
  orderId: {
    type: String,
    default: ''
  }
})

const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const listParams = ref({
  time: '',
  startTime: '',
  endTime: ''
})
const timePeriod = ref([])
const refContentTable = ref(null)
const loading = ref(false)
const columns = ref(
  Array.from({ length: 25 }, (v, i) => `${i.toString().padStart(2, '0')}:00`)
)
const tableData = ref([
  {
    // header: '08:00',
    span: 1,
    name: '山水国际'
  }
])
const columnWidthObj = ref({})
const total = ref(0)
const pageSize = ref(10)
const pageNum = ref(1)
const addOrEditVisible = ref(false)
const addOrEditType = ref('detail')
const rowId = ref('')
const detailVisible = ref(false)

const getTableList = () => {
  loading.value = true
  tableData.value = []
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    vehicleId: props.vehicleId,
    orderId: props.orderId,
    startTime: listParams.time ? listParams.time + '00:00:00' : '',
    endTime: listParams.time ? listParams.time + '23:59:59' : ''
  }
  g_api.fleet
    .apiScheduleList(params)
    .then(({ code, data }) => {
      if (code === '200' && data) {
        tableData.value = data.items
        total.value = data.total
        let arr = []
        data.items.forEach(item => {
          item.header = item.startTime.slice(11, 13)
          item.span = item.endTime.slice(11, 13) - item.startTime.slice(11, 13)
          arr.push(item)
        })
        console.log('arr', arr)
        useTableColumnWidth({
          refTable: refContentTable.value
        }).getTableColumnWidth(data => {
          columnWidthObj.value = data
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function isTimeInInterval(targetTime, intervalStart) {
  const target = new Date(targetTime)
  const start = new Date(intervalStart)
  const end = new Date(start)
  end.setHours(start.getHours() + 1)

  return target >= start && target < end
}

onMounted(() => {
  getTableList()
})

const handleClose = () => {
  dialogVisible.value = false
}

const disabledDate = time => {
  return false
}

const handleQuery = () => {
  pageNum.value = 1
  getTableList()
}

const handleReset = () => {
  Object.assign(listParams.value, {
    time: '',
    startTime: '',
    endTime: ''
  })
  timePeriod.value = []
  handleQuery()
}

const handleCreate = () => {
  addOrEditVisible.value = true
  addOrEditType.value = 'add'
}

const handleDelete = row => {
  g_utils
    .deleteConfirm()
    .then(() => {
      loading.value = true
      g_api.fleet
        .apiScheduleDelete({
          vehicleScheduleId: row.id
        })
        .then(res => {
          if (res.code === '200') {
            ElMessage.success(res.message)
            handleQuery()
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
    .catch(() => {})
}

const handleDetailDialog = row => {
  detailVisible.value = true
  rowId.value = row.id
}

const handleEditDialog = row => {
  addOrEditVisible.value = true
  addOrEditType.value = 'edit'
  rowId.value = row.id
}

defineExpose({
  refContentTable
})
</script>

<style lang="scss">
.dialog-table-class {
  display: flex;
  .content-container {
    height: initial;
    .base-table-container {
      padding: 0;
    }
  }
}
</style>

<style lang="scss" scoped></style>
